package inc.prada.android.ext.view;

import java.util.ListIterator;
import java.util.Vector;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class SpectrumView extends View implements ISpectrum {

	private Vector<Integer> screen;
	private int xResolution;
	private int yResolution;
	private Paint highlightPaint;
	private Paint bgPaint;
	private int HIGHLIGHT_COLOR = Color.YELLOW;
	

	
	private void setup(){
		highlightPaint = new Paint();
		highlightPaint.setColor(HIGHLIGHT_COLOR);
		bgPaint = new Paint();
		bgPaint.setColor(Color.WHITE);
	}
	
	public SpectrumView(Context context){
		super(context);
		setup();
	}
	
	public SpectrumView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setup();
	}

	public void init(int xResolution, int yResolution) {
		this.xResolution = xResolution;
		this.yResolution = yResolution;
		screen = new Vector<Integer>(xResolution);
	}

	protected void onDraw(Canvas canvas) {
		System.out.println("call onDraw");
		flushScreen(canvas);
		if (screen != null) {
			int xRes = canvas.getWidth() / this.xResolution;
			int yRes = canvas.getHeight() / this.yResolution;

			ListIterator<Integer> interator = screen.listIterator();
			int count = 0;
			while (interator.hasNext()) {
				int v = interator.next().intValue();
				System.out.println("draw:"+v+" x:"+count);
				canvas.drawRect(
						getPosition(count++, v, xRes,
								yRes), this.highlightPaint);
			}
		} else {
			drawReady(canvas);
		}
	}

	

	private void flushScreen(Canvas canvas) {
		canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), bgPaint);
	}

	private void drawReady(Canvas canvas) {
	}

	private Rect getPosition(int x, int y, int xRes, int yRes) {
//		return new Rect(x * xRes, y * yRes, (x + 1) * xRes, (y + 1) * yRes);
		return new Rect(0 ,x * xRes,  (y + 1) * yRes,(x + 1) * xRes );
	}

	public void add(int value) {
		if (screen.size() >= screen.capacity())
			screen.removeElement(screen.lastElement());
		screen.add(0, value);
		System.out.println("screen size " + screen.size());
	}

	@Override
	public void flush() {
		this.postInvalidate();
	}

	@Override
	public View getView() {
		return this;
	}

}
